# PowerShell服务启动脚本 - 避免缓冲区问题
param(
    [switch]$Debug,
    [switch]$NoConsole,
    [int]$Port = 6731
)

Write-Host "=== HIS退费服务启动脚本 ===" -ForegroundColor Green
Write-Host "启动时间: $(Get-Date)" -ForegroundColor Yellow

# 设置PowerShell缓冲区大小
$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size(120, 3000)

# 设置控制台窗口大小
$host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size(120, 50)

# 获取当前目录
$currentDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $currentDir

Write-Host "当前目录: $currentDir" -ForegroundColor Cyan

# 检查端口是否被占用
$portInUse = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue
if ($portInUse) {
    Write-Host "端口 $Port 已被占用，正在尝试终止占用进程..." -ForegroundColor Red
    $process = Get-Process -Id $portInUse.OwningProcess -ErrorAction SilentlyContinue
    if ($process) {
        Write-Host "终止进程: $($process.ProcessName) (PID: $($process.Id))" -ForegroundColor Yellow
        Stop-Process -Id $process.Id -Force
        Start-Sleep -Seconds 2
    }
}

# 设置环境变量
$env:ASPNETCORE_ENVIRONMENT = if ($Debug) { "Development" } else { "Production" }
$env:ASPNETCORE_URLS = "http://0.0.0.0:$Port"

# 清理日志文件（保留最近7天）
Write-Host "清理旧日志文件..." -ForegroundColor Yellow
$logPath = Join-Path $currentDir "logs"
if (Test-Path $logPath) {
    Get-ChildItem -Path $logPath -Name "*.log" | 
        Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
        Remove-Item -Force -ErrorAction SilentlyContinue
    Write-Host "日志清理完成" -ForegroundColor Green
}

# 构建并运行服务
Write-Host "开始构建服务..." -ForegroundColor Yellow
dotnet build --configuration Release
if ($LASTEXITCODE -ne 0) {
    Write-Host "构建失败，退出码: $LASTEXITCODE" -ForegroundColor Red
    exit $LASTEXITCODE
}

Write-Host "构建成功，开始启动服务..." -ForegroundColor Green

# 根据参数选择启动方式
if ($NoConsole) {
    Write-Host "启动无控制台模式..." -ForegroundColor Yellow
    Start-Process "dotnet" -ArgumentList "run --no-build --configuration Release" -NoNewWindow -RedirectStandardOutput "logs/console-$(Get-Date -Format 'yyyyMMdd_HHmmss').log" -RedirectStandardError "logs/error-$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
} else {
    Write-Host "启动控制台模式（日志已重定向到文件）..." -ForegroundColor Yellow
    Write-Host "服务日志将输出到: logs/service-$(Get-Date -Format 'yyyyMMdd').log" -ForegroundColor Cyan
    Write-Host "按 Ctrl+C 停止服务" -ForegroundColor Yellow
    Write-Host "================================" -ForegroundColor Green
    
    # 使用Start-Process启动，避免PowerShell缓冲区问题
    Start-Process "dotnet" -ArgumentList "run --no-build --configuration Release" -NoNewWindow -Wait
}

Write-Host "服务已停止" -ForegroundColor Red